package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ShopMapper shopMapper;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryGetById(Long id) throws InterruptedException {
        //缓存穿透
//        Shop shop = cacheClient
//                .queryWithPassThroucgh(CACHE_SHOP_KEY, id, CACHE_SHOP_TTL, TimeUnit.MINUTES, Shop.class, this::getById);

        //缓存击穿（互斥锁）
//        Shop shop = queryWithMutex(id);

        //缓存击穿（逻辑过期时间）
        Shop shop = cacheClient.queryWithLogicalExpare(CACHE_SHOP_KEY, LOCK_REDISDATA_KEY, id, 10L, LOCK_SHOP_TTL, TimeUnit.SECONDS, TimeUnit.SECONDS, Shop.class, this::getById);

        //返回商铺信息
        return Result.ok(shop);
    }

    //修改逻辑过期时间，让redis缓存永久有效，使用自定义字段逻辑时间
    public void saveShop2Redis(Long id, Long expireSeconds){
        //1.查询店铺数据
        Shop shop = getById(id);

        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        //3.写入Redis
        String jsonRedisData = JSONUtil.toJsonStr(redisData);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, jsonRedisData);
    }

    //缓存击穿(互斥锁实现）
    public Shop queryWithMutex(Long id) throws InterruptedException {
        //1.根据id从redis中查询商铺缓存
        String shopKey = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(shopKey);

        // 2.如果为空字符串，则返回错误信息（缓存穿透）
        if ("".equals(shopJson)) {
            return null;
        }

        //3.如过存在则直接返回商铺信息
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        //尝试加锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            //如果加锁失败，说明此时有人在查数据库。休眠一段时间重新查缓存..
            if (!tryLock(lockKey)) {
                Thread.sleep(50);
                //递归重新开始这个方法
                queryWithMutex(id);
            }

            //加锁成功则查询数据库并更新缓存
            //但应先做二次校验，可能刚查完别人就恰好更新好缓存
            String doubleShopJson = stringRedisTemplate.opsForValue().get(shopKey);
            if ("".equals(doubleShopJson)) {
                return null;
            }
            if (StrUtil.isNotBlank(doubleShopJson)) {
                shop = JSONUtil.toBean(doubleShopJson, Shop.class);
                return shop;
            }

            //校验完再去更新缓存
            //4.不存在则查询数据库
            shop = getById(id);

            //5.若数据库中不存在则直接返回错误
            if (shop == null) {
                // 6.将空值写入redis中（应对缓存穿透）
                stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            //7.若数据库中存在则更新redis,并设置过期时间（超时剔除）
            stringRedisTemplate.opsForValue().set(shopKey, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unLock(lockKey);
        }

        //8.并返回商铺信息
        return shop;
    }

    //加锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //解锁
    private boolean unLock(String key) {
        Boolean flag = stringRedisTemplate.delete(key);
        return BooleanUtil.isTrue(flag);
    }


    @Override
    @Transactional
    public Result updateShopById(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺ID不能为空");
        }

        //1.先更新数据库
        updateById(shop);

        //2.再删缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        //3.返回
        return Result.ok();
    }
}
